
package ndk;


/**
 * crc加密工具类.
 *
 * @author lambo
 */
public class CrcUtil {

	public static void main(String args[]){
		String aa = "7F0600012F011F050503";
		byte[] data = getCrcX1ModemByte(hex2byte(aa));
		System.out.println(bytesToHex(data));
		
	}
	
	/**
     * 向串口发送数据转为字节数组
     *
     * @param hex 十六进制数转byte数组
     */
    public static byte[] hex2byte(String hex) {
        String digital = "0123456789ABCDEF";
        String hex1 = hex.replace(" ", "");
        char[] hex2char = hex1.toCharArray();
        byte[] bytes = new byte[hex1.length() / 2];
        byte temp;
        for (int p = 0; p < bytes.length; p++) {
            temp = (byte) (digital.indexOf(hex2char[2 * p]) * 16);
            temp += digital.indexOf(hex2char[2 * p + 1]);
            bytes[p] = (byte) (temp & 0xff);
        }
        return bytes;
    }

	/**
     * 字节数组转16进制
     *
     * @param bytes 需要转换的byte数组
     * @return 转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /**
     * 获取byte类型的数据.
     *
     * @param data data.
     * @return byte[].
     */
    public static byte[] getCrcX1ModemByte(byte[] data) {
        byte[] value = new byte[2];
        int crc = getCrcX1Modem(data);
        value[0] = (byte) (crc & 0xff);
        value[1] = (byte) ((crc >> 8) & 0xff);
        return value;
    }

    /**
     * crc x modem签名.
     *
     * @param bytes bytes.
     * @return test.
     */
    public static int getCrcX1Modem(byte[] bytes) {
        // initial value
        int crc = 0x00;
        int polynomial = 0x1021;
        for (int index = 0; index < bytes.length; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) {
                    crc ^= polynomial;
                }
            }
        }
        crc &= 0xffff;
        return crc;
    }

}
